package com.pyue.eam.regi.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pyue.eam.admin.api.entity.regi.ClientAddrEntity;
import com.pyue.eam.admin.api.entity.regi.ClientLibEntity;
import com.pyue.eam.regi.mapper.ClientLibMapper;
import com.pyue.eam.regi.service.ClientLibService;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 客户表
 *
 * @author lucc
 * @date 2023-10-12 20:38:12
 */
@Service
@AllArgsConstructor
public class ClientLibServiceImpl extends ServiceImpl<ClientLibMapper, ClientLibEntity> implements ClientLibService {

    @Override
    public List<ClientLibEntity> dataList() {
        List<ClientLibEntity> libEntityList = list();

        if (CollUtil.isNotEmpty(libEntityList)) {
            libEntityList.forEach(e -> {
                List<ClientAddrEntity> baseAddrEntityList = baseMapper.listClientBaseByClientId(e.getClientId());
                e.setBaseAddrList(baseAddrEntityList);
            });
        }

        return libEntityList;
    }

    @Override
    public ClientLibEntity getDataById(Long clientId) {
        ClientLibEntity libEntity = getById(clientId);

        if (libEntity != null) {
            List<ClientAddrEntity> baseAddrEntityList = baseMapper.listClientBaseByClientId(clientId);
            libEntity.setBaseAddrList(baseAddrEntityList);
        }

        return libEntity;
    }

    @Override
    public Boolean updateDataById(ClientLibEntity clientLib) {
        baseMapper.removeClientAddrByClientId(clientLib.getClientId());

        if (CollUtil.isNotEmpty(clientLib.getBaseAddrList())) {
            clientLib.getBaseAddrList().forEach(e -> e.setClientId(clientLib.getClientId()).setId(null));
            baseMapper.saveBatchClientAddr(clientLib.getBaseAddrList());
        }
        return updateById(clientLib);
    }

    @Override
    public Boolean saveData(ClientLibEntity clientLib) {
        save(clientLib);
        if (CollUtil.isNotEmpty(clientLib.getBaseAddrList())) {
            clientLib.getBaseAddrList().forEach(e -> e.setClientId(clientLib.getClientId()));
            baseMapper.saveBatchClientAddr(clientLib.getBaseAddrList());
        }

        return Boolean.TRUE;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean removeDataByIds(List<Long> idList) {
        for (Long clientId : idList) {
            baseMapper.removeClientAddrByClientId(clientId);
        }
        this.removeBatchByIds(idList);
        return Boolean.TRUE;
    }

}
